<?php
//error_reporting(E_ALL);
//ini_set('display_errors','On');
#########################################################
#                                                       #
#  Sofortüberweisung / INSTANTBANKTRANSFER payment      #
#  method class                                         #
#  This module is used for real time processing of      #
#  German Bankdata of customers.                        #
#                                                       #
#  Copyright (c) 2009 Novalnet AG                       #
#                                                       #
#  Released under the GNU General Public License        #
#  Created by Zhang jz@novalnet.de                      #
#  This free contribution made by request.              #
#  If you have found this script usefull a small        #
#  recommendation as well as a comment on merchant form #
#  would be greatly appreciated.                        #
#                                                       #
#  Script : novalnet_instantbanktransfer.php            #
#  Version: 1.0.1 2011-06-21                            #
#                                                       #
#########################################################


class novalnet_instantbanktransfer {
	var $code;
	var $title;
	var $description;
	var $enabled;
	var $blnDebug;
	var $key;
	var $implementation;
	var $KEY = 33;
	var $is_ajax = false;

  function novalnet_instantbanktransfer() {
	global $order, $novalnet, $db;
	$this->key = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_PASSWORD; #'z2Vw3E4j';
	$this->code            = 'novalnet_instantbanktransfer';
	$this->form_action_url = 'https://payport.novalnet.de/online_transfer_payport';
	$this->title           = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEXT_TITLE;
	$this->public_title    = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEXT_PUBLIC_TITLE;
	$this->description     = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEXT_DESCRIPTION;
	$this->sort_order      = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_SORT_ORDER;
	$this->enabled         = ((MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_STATUS == 'True') ? true : false);
	$this->blnDebug        = false; #todo: set to false for live system
	$this->proxy           = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_PROXY;
	$this->implementation  = '';#'JAVA', 'PHP', '', if empty, then equal to 'PHP'
	$this->db = $db;
    if ($_REQUEST['hash2']){
      if (strtoupper($this->implementation) == 'JAVA'){#Java encoded
        if ( $_REQUEST['auth_code'] != md5(MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_AUTH_CODE.strrev($this->key)) ){
          $err = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEXT_HASH_ERROR.'; wrong auth_code!';
          $payment_error_return = 'payment_error=novalnet_instantbanktransfer&error='.$_REQUEST['status_text'].'; '.utf8_encode($err);
			if ($novalnet->is_ajax) {
				redirect(href_link($novalnet->returnURL, $payment_error_return, 'SSL', true, false));
			} else {
				redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}
        }
        $_REQUEST['auth_code']  = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_AUTH_CODE;#todo: check?
        $_REQUEST['product_id'] = $this->encode4java($_REQUEST['product'],   'bindec');
        $_REQUEST['tariff_id']  = $this->encode4java($_REQUEST['tariff'],    'bindec');
        $_REQUEST['amount']     = $this->encode4java($_REQUEST['amount'],    'bindec');
        $_REQUEST['test_mode']  = $this->encode4java($_REQUEST['test_mode'], 'bindec');
        $_REQUEST['uniqid']     = $this->encode4java($_REQUEST['uniqid'],    'bindec');
        if (!$this->checkHash4java($_REQUEST)){
          $err = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEXT_HASH_ERROR;
          $payment_error_return = 'payment_error=novalnet_instantbanktransfer&error='.$_REQUEST['status_text'].'; '.utf8_encode($err);
			if ($novalnet->is_ajax) {
				redirect(href_link($novalnet->returnURL, $payment_error_return, 'SSL', true, false));
			} else {
				redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}
        }
      }else{
        if (!$this->checkHash($_REQUEST)){
          $err = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEXT_HASH_ERROR;
          $payment_error_return = 'payment_error=novalnet_instantbanktransfer&error='.$_REQUEST['status_text'].'; '.utf8_encode($err);
		  	if ($novalnet->is_ajax) {
				redirect(href_link($novalnet->returnURL, $payment_error_return, 'SSL', true, false));
			} else {
				redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}
        }else{
        $_REQUEST['auth_code']  = $this->decode($_REQUEST['auth_code']);
        $_REQUEST['product_id'] = $this->decode($_REQUEST['product_id']);
        $_REQUEST['tariff_id']  = $this->decode($_REQUEST['tariff_id']);
        $_REQUEST['amount']     = $this->decode($_REQUEST['amount']);
        $_REQUEST['test_mode']  = $this->decode($_REQUEST['test_mode']);
        $_REQUEST['uniqid']     = $this->decode($_REQUEST['uniqid']);
        }
      }
    }
    if ((int)MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_ORDER_STATUS_ID > 0) {
      $this->order_status = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_ORDER_STATUS_ID;
    }
    if (is_object($order)) $this->update_status();
  }

  function update_status() {
    global $order, $novalnet, $db;
    if ( ($this->enabled == true) && ((int)MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_ZONE > 0) ) {
      $check_flag = false;
      $check_query = $this->db->db_query("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_ZONE . "' and zone_country_id = '" . $order->billing['country']['id'] . "' order by zone_id");
        while ($check = db_fetch_array($check_query)) {
          if ($check['zone_id'] < 1) {
            $check_flag = true;
            break;
          } elseif ($check['zone_id'] == $order->billing['zone_id']) {
            $check_flag = true;
            break;
          }
        }
      if ($check_flag == false) {
        $this->enabled = false;
      }
    }
  }
 
	function javascript_validation() {
		return false;
	}
 
	function selection() {
	global $xtPrice, $order,$_POST;
	$selection = array('id' => $this->code,
					   'module' => $this->public_title,
					   'fields' => array(array('title' => '<!--b><font color="red">Achtung:<br />Klicken Sie bitte UNBEDINGT auf den Button &lt;Zur&uuml;ck zum Shop&gt;, wenn Sie auf der Transaktionsabschlu&szlig;seite Ihrer Bank die Transaktion durchgef&uuml;hrt haben. Ansonsten wird Ihe Shop-Bestellung trotz erfolgter Transaktion nicht abgeschlossen.</font></b-->')
				   ));
		if(function_exists(get_percent))
		{
			$selection['module_cost'] = $GLOBALS['ot_payment']->get_percent($this->code);
		}
	return $selection;
	}

	
	function pre_confirmation_check($vars = '') {
	global $order, $novalnet,$_POST;
	$error = '';
		if(!MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_VENDOR_ID || !MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_AUTH_CODE || !MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_PRODUCT_ID || !MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TARIFF_ID)
		{
			$error = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEXT_JS_NN_MISSING;
		}
		if($error!='') {
			$payment_error_return = 'payment_error=' . $this->code . '&error=' . urlencode(utf8_encode($error));
		if ($novalnet->is_ajax) {
			$_SESSION['checkout_payment_error'] = $payment_error_return;
		} else {
			redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
		}
		}
	}
	public function findTotalAmount(){
	global $order;
		if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1) {
		$total = $order->info['total'] + $order->info['tax'];
		} else {
		$total = $order->info['total'];
		}
		if (preg_match('/[^\d\.]/', $total) or !$total){
			$err                      = 'amount ('.$total.') is empty or has a wrong format';
			$payment_error_return     = 'payment_error='.$this->code.'&error='.utf8_encode($err);
		if ($novalnet->is_ajax) {
			$_SESSION['checkout_payment_error'] = $payment_error_return;
		} else {
			redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
		}
		}
		$amount = sprintf('%0.2f', $total);
		$amount = preg_replace('/^0+/', '', $amount);
		$amount = str_replace('.', '', $amount);
	return $amount;
	}

	function confirmation() {
	global $_POST, $order;
		if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1) {
		$total = $order->info['total'] + $order->info['tax'];
		} else {
		$total = $order->info['total'];
		}
	$_SESSION['nn_total'] = sprintf('%.2f', $total);
	return $confirmation;
	}

	function process_button() {
    global $_POST, $order, $currencies, $customer_id,$novalnet, $db;  
    $customer_query = $this->db->db_query("SELECT customers_gender, customers_dob, customers_fax FROM ". TABLE_CUSTOMERS . " WHERE customers_id='". (int)$customer_id ."'");
    if ($customer_query->_numOfRows) {
		$customer['customers_gender']=$customer_query->fields['customers_gender'];
		$customer['customers_dob']=$customer_query->fields['customers_dob'];
		$customer['customers_fax']=$customer_query->fields['customers_fax'];	
	}
    list($customer['customers_dob'], $extra) = explode(' ', $customer['customers_dob']);
    $amount = $this->findTotalAmount();
    $vendor_id    = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_VENDOR_ID;
    $auth_code    = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_AUTH_CODE;
    $product_id   = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_PRODUCT_ID;
    $tariff_id    = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TARIFF_ID;
    $uniqid       = uniqid();
    $test_mode    = (strtolower(MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEST_MODE) == 'true' or MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEST_MODE == '1')? 1: 0;
	$_SESSION['test_mode_instantbanktransfer']=$test_mode;
    if (strtoupper($this->implementation) == 'JAVA'){
      $uniqid       = time();#must ne a long integer
      $hash         = md5($auth_code.$product_id.$tariff_id.$amount.$test_mode.$uniqid.strrev($this->key));
      $auth_code    = md5($auth_code.strrev($this->key));
      $product_id   = $this->encode4java($product_id, 'decbin');
      $tariff_id    = $this->encode4java($tariff_id, 'decbin');
      $amount       = $this->encode4java($amount, 'decbin');
      $test_mode    = $this->encode4java($test_mode, 'decbin');
      $uniqid       = $this->encode4java($uniqid, 'decbin');

    }else{
      $auth_code    = $this->encode($auth_code);
      $product_id   = $this->encode($product_id);
      $tariff_id    = $this->encode($tariff_id);
      $amount       = $this->encode($amount);
      $test_mode    = $this->encode($test_mode);
      $uniqid       = $this->encode($uniqid);
      $hash         = $this->hash(array('auth_code' => $auth_code, 'product_id' => $product_id, 'tariff' => $tariff_id, 'amount' => $amount, 'test_mode' => $test_mode, 'uniqid' => $uniqid));
    }
    $user_ip      = $this->getRealIpAddr();
		if ($novalnet->is_ajax) {
			$checkout_url = href_link($novalnet->returnURL, '', 'SSL');
		} else {
			$checkout_url = href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL');
		}
	if(strstr($checkout_url, '?'))
    {
      $checkout_url = str_replace(' ', '', $checkout_url);
      if(substr($checkout_url,-1)=='?')
           $error_url = $checkout_url.'payment_error=novalnet_instantbanktransfer&error=$ERROR_MESSAGE ($STATUS)';
      else $error_url = $checkout_url.'&payment_error=novalnet_instantbanktransfer&error=$ERROR_MESSAGE ($STATUS)';
    }
    else $error_url = $checkout_url.'?payment_error=novalnet_instantbanktransfer&error=$ERROR_MESSAGE ($STATUS)';
    $process_button_string =
      draw_hidden_field('vendor',    $vendor_id) .#Pflicht
      draw_hidden_field('auth_code', $auth_code) .
      draw_hidden_field('product',   $product_id) .
      draw_hidden_field('tariff',    $tariff_id) .
      draw_hidden_field('test_mode', $test_mode) .
      draw_hidden_field('uniqid',    $uniqid) .
      draw_hidden_field('amount',    $amount) .
      draw_hidden_field('hash',      $hash) .
      draw_hidden_field('key', $this->KEY) .#Pflicht
      draw_hidden_field('currency',  $order->info['currency']) .
      draw_hidden_field('first_name', $this->html_to_utf8($order->customer['firstname'])) .
      draw_hidden_field('last_name', $this->html_to_utf8($order->customer['lastname'])) .
      draw_hidden_field('gender',    'u') .
      draw_hidden_field('email',     $order->customer['email_address']) .
      draw_hidden_field('street',    $this->html_to_utf8($order->customer['street_address'])) .
      draw_hidden_field('search_in_street', '1') .
      draw_hidden_field('city',      $this->html_to_utf8($order->customer['city'])) .
      draw_hidden_field('zip',       $order->customer['postcode']) .
      draw_hidden_field('country',   $order->customer['country']['iso_code_2']) .
      draw_hidden_field('country_code', $order->customer['country']['iso_code_2']) .
      draw_hidden_field('lang',      MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEXT_LANG) .#default: 'DE'
      draw_hidden_field('language',  MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEXT_LANG) .#default: 'DE'
      draw_hidden_field('remote_ip', $user_ip) . #Pflicht
      draw_hidden_field('tel', $order->customer['telephone']) .
      draw_hidden_field('fax', $customer['customers_fax']) .
      draw_hidden_field('birth_date', $customer['customers_dob']) .
      draw_hidden_field('return_url', href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL')) .
      draw_hidden_field('return_method', 'POST') .
      draw_hidden_field('error_return_url', $error_url) .
      draw_hidden_field('user_variable_0', str_replace(array('http://', 'www.'), array('', ''), $_SERVER['SERVER_NAME'])) .
      draw_hidden_field('implementation', strtoupper($this->implementation)) .
      draw_hidden_field('error_return_method', 'POST');
	  $process_button_string .= $this->getParams4InstantBankTransfer();
    return $process_button_string;
  }

  function before_process() {
    global $_POST, $order, $currencies, $customer_id, $novalnet, $db;
	if (strtolower(MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEST_MODE) == 'true' or MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEST_MODE == '1'){
		$order->info['comments'] .= MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEST_ORDER_MESSAGE;
    } elseif ($_SESSION['test_mode_instantbanktransfer']==1) {
		$order->info['comments'] .= MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEST_ORDER_MESSAGE;
	}
    	$order->info['comments'] .= MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TID_MESSAGE.$_POST['tid'];
		$_SESSION['nn_tid_instantbanktransfer'] = $_POST['tid']; #todo: 
  }

  function after_process() {
    global $order, $customer_id, $insert_id, $novalnet, $db;
    if ($this->order_status){
      $this->db->db_query("UPDATE ".TABLE_ORDERS." SET orders_status='".$this->order_status."' WHERE orders_id='".$insert_id."'");
    }
    $product_id = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_PRODUCT_ID;
    $tariff_id = MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TARIFF_ID;
    $url = 'https://payport.novalnet.de/paygate.jsp';
    $urlparam = 'vendor='.MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_VENDOR_ID.'&product='.$product_id.'&key=6&tariff='.$tariff_id;
	$urlparam .= '&order_no='.$insert_id;
    $urlparam .= '&auth_code='.MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_AUTH_CODE.'&status=100&tid='.$_SESSION['nn_tid_instantbanktransfer'].'&reference=BNR-'.$insert_id.'&vwz2='.MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEXT_ORDERNO.''.$insert_id.'&vwz3='.MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEXT_ORDERDATE.''.date('Y-m-d H:i:s');
    list($errno, $errmsg, $data) = $novalnet->perform_https_request($url, $urlparam);
    if ($errno or $errmsg) {
      $order->info['comments'] .= '. func perform_https_request returned Errorno : '.$errno.', Error Message : '.$errmsg;
      $payment_error_return = 'payment_error=' . $this->code . '&error=' .utf8_encode($errmsg). '('.$errno.')';
	  if ($novalnet->is_ajax) {
				$_SESSION['checkout_payment_error'] = $payment_error_return;
			} else {
				redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}
    }
    $_SESSION['nn_tid_instantbanktransfer'] = '';
    return false;
  }

  function get_error() {
    global $HTTP_GET_VARS, $_GET;
    if(count($HTTP_GET_VARS)==0 || $HTTP_GET_VARS=='') $HTTP_GET_VARS = $_GET;
    $error = array('title' => MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEXT_ERROR, 'error' => stripslashes(utf8_decode($HTTP_GET_VARS['error'])));
    return $error;
  }

	function check() {
	global $order, $novalnet, $db;
	if (!isset($this->_check)) {
		$check_query = $this->db->db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_STATUS'");
		$this->_check = $check_query->_numOfRows;
	}
		return $this->_check;
	}

	function install() {
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_ALLOWED', '', '6', '0', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_STATUS', 'True', '6', '1', 'cfg_select_option(array(\'True\', \'False\'), ', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEST_MODE', 'True', '6', '2', 'cfg_select_option(array(\'True\', \'False\'), ', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_PASSWORD', '', '6', '3', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_VENDOR_ID', '', '6', '4', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_AUTH_CODE', '', '6', '5', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_PRODUCT_ID', '', '6', '6', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TARIFF_ID', '', '6', '7', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_SORT_ORDER', '0', '6', '8', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, use_function, date_added) values ('MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_ORDER_STATUS_ID', '0', '6', '9', 'cfg_pull_down_order_statuses(', 'get_order_status_name', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, use_function, set_function, date_added) values ('MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_ZONE', '0', '6', '10', 'get_zone_class_title', 'cfg_pull_down_zone_classes(', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_INFO', '', '6', '11', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_PROXY', '', '6', '12', now())");
  }
   
	function remove() {
	global $db;
	$this->db->db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
	}

	function keys() {
    return array('MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_ALLOWED', 'MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_STATUS', 
    'MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TEST_MODE','MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_VENDOR_ID', 'MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_AUTH_CODE', 'MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_PRODUCT_ID', 'MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_TARIFF_ID', 'MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_INFO', 'MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_SORT_ORDER', 'MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_ORDER_STATUS_ID', 
    'MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_ZONE', 'MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_PASSWORD', 'MODULE_PAYMENT_NOVALNET_INSTANTBANKTRANSFER_PROXY');
	}

	function html_to_utf8 ($data)
	{
		$data = utf8_encode($data);
		return preg_replace("/\\&\\#([0-9]{3,10})\\;/e", '$this->_html_to_utf8("\\1")', $data);
	}

	function _html_to_utf8 ($data)
	{
		if ($data > 127)
		{
			$i = 5;
			while (($i--) > 0)
			{
				if ($data != ($a = $data % ($p = pow(64, $i))))
				{
					$ret = chr(base_convert(str_pad(str_repeat(1, $i + 1), 8, "0"), 2, 10) + (($data - $a) / $p));
					for ($i; $i > 0; $i--)
						$ret .= chr(128 + ((($data % pow(64, $i)) - ($data % ($p = pow(64, $i - 1)))) / $p));
					break;
				}
			}
		}
		else
		{
			#$this->debug2("&#$data;");
			$ret = "&#$data;";
		}
		return $ret;
	}

	function debug2($text)
	{
		$fh = fopen('/tmp/debug2.txt', 'a+');
		if (gettype($text) == 'class' or gettype($text) == 'array')
		{
			$text = serialize($text);
			fwrite($fh, $text);
		}
		else
		{
			fwrite($fh, date('H:i:s ').$text."\n");
		}
		fclose($fh);
	}

  function isPublicIP($value)
  {
        if(!$value || count(explode('.',$value))!=4) return false;
        return !preg_match('~^((0|10|172\.16|192\.168|169\.254|255|127\.0)\.)~', $value);
  }

  function getRealIpAddr()
  {
        if($this->isPublicIP($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR'];
        if($iplist=explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            if($this->isPublicIP($iplist[0])) return $iplist[0];
        }
        if ($this->isPublicIP($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP'];
        if ($this->isPublicIP($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
        if ($this->isPublicIP($_SERVER['HTTP_FORWARDED_FOR']) ) return $_SERVER['HTTP_FORWARDED_FOR'];

        return $_SERVER['REMOTE_ADDR'];
  }
 
	function getParams4InstantBankTransfer()
	{
		$params = draw_hidden_field('user_variable_0', (str_replace(array('http://', 'www.'), array('', ''), HTTP_SERVER)));
		return $params;
	}
	
	function encode($data)
	{
	$data = trim($data);
	if ($data == '') return'Error: no data';
	if (!function_exists('base64_encode') or !function_exists('pack') or !function_exists('crc32')){return'Error: func n/a';}

	try {
	  $crc = sprintf('%u', crc32($data));
	  $data = $crc."|".$data;
	  $data = bin2hex($data.$this->key);
	  $data = strrev(base64_encode($data));
	}catch (Exception $e){
	  echo('Error: '.$e);
	}
	return $data;
	}
	
	function decode($data)
	{
		$data = trim($data);
		if ($data == '') {return'Error: no data';}
		if (!function_exists('base64_decode') or !function_exists('pack') or !function_exists('crc32')){return'Error: func n/a';}

		try {
		  $data =  base64_decode(strrev($data));
		  $data = pack("H".strlen($data), $data);
		  $data = substr($data, 0, stripos($data, $this->key));
		  $pos = strpos($data, "|");
		  if ($pos === false){
			return("Error: CKSum not found!");
		  }
		  $crc = substr($data, 0, $pos);
		  $value = trim(substr($data, $pos+1));
		  if ($crc !=  sprintf('%u', crc32($value))){
			return("Error; CKSum invalid!");
		  }
		  return $value;
		}catch (Exception $e){
		  echo('Error: '.$e);
		}
	}
	
	function hash($h)
	{
		global $amount_zh;
		if (!$h) return'Error: no data';
		if (!function_exists('md5')){return'Error: func n/a';}
		return md5($h['auth_code'].$h['product_id'].$h['tariff'].$h['amount'].$h['test_mode'].$h['uniqid'].strrev($this->key));
	}
  
  function checkHash($request)
  {
    if (!$request) return false; 
    $h['auth_code']  = $request['auth_code'];
    $h['product_id'] = $request['product'];
    $h['tariff']     = $request['tariff'];
    $h['amount']     = $request['amount'];
    $h['test_mode']  = $request['test_mode'];
    $h['uniqid']     = $request['uniqid'];
	if ($request['hash2'] != $this->hash($h)){
      return false;
    }
    return true;
  }

  function checkHash4java($request)
  {
    if (!$request) return false; 
    $h['auth_code']  = $request['auth_code'];
    $h['product_id'] = $request['product_id'];
    $h['tariff']     = $request['tariff_id'];
    $h['amount']     = $request['amount'];
    $h['test_mode']  = $request['test_mode'];
    $h['uniqid']     = $request['uniqid'];
    if ($request['hash2'] != $this->hash($h)){
      return false;
    }
    return true;
  }

  function encode4java($data = '', $func = ''){
    $salt = 1010;
    if (!isset($data) or trim($data) == '' or !$func){
      return'Error: missing arguments: $str and/or $func!';
    }
    if ($func != 'decbin' and $func != 'bindec'){
      return'Error: $func has wrong value!';
    }
    if ($func == 'decbin'){
      return decbin(intval($data) + intval($salt));
    }else{
      return bindec($data) - intval($salt);
    }
  }
}

?>
